package daily;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ConditionThreadCommunication {
	
	private void init(){
		final Business business=new Business();
		new Thread(new Runnable(){

			@Override
			public void run() {
				for(int i=0;i<50;i++){
					business.doSub(i);
				}
				
			}
			
		}).start();
		
		for(int i=0;i<50;i++){
			business.doMain(i);
		}
	}

	public static void main(String[] args) {
		ConditionThreadCommunication ttc=new ConditionThreadCommunication();
		ttc.init();
	}
	
	
	class Business{
		private boolean isSub=true;
		private Lock lock=new ReentrantLock();
		private Condition condition=lock.newCondition();
		public  void doSub(int count){
			lock.lock();
			try {
				while(!isSub){
					try {
						condition.await();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				
				for(int i=0;i<10;i++){
					System.out.println(count+" loop "+ i+"    doSub--------");
				}
				isSub=false;
				condition.signal();
			}finally{
				lock.unlock();
			}
			
		}
		
		public  void doMain(int count){
			lock.lock();
			try {
				while(isSub){
					try {
						condition.await();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				
				for(int i=0;i<50;i++){
					System.out.println(count+" loop "+ i+"    doMain--------");
				}
				isSub=true;
				condition.signal();
			} finally{
				lock.unlock();
			}
		}
	}
}
